/*
 * @lc app=leetcode.cn id=110 lang=cpp
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        bool flag = true;
        dfs(root, flag);
        return flag;
    }
    int dfs(TreeNode* root, bool& flag)
    {
        if(root == NULL)
            return 0;
        int lh = dfs(root->left, flag);
        if(flag == false) return lh;
        int rh = dfs(root->right, flag);
        if(abs(lh - rh) > 1)
        {
            flag = false;
        }
        return max(lh, rh) + 1;
    }
};
// @lc code=end

